import { TilingSprite ,Texture} from "pixi.js";
import {TexturePool} from "@/utils/TexturePool.js";
import { ImageManager } from "@/managers/ImageManager.js";

export class Sprite_Tiling extends TilingSprite{
    constructor(source,width=0,height=0){
        let texture=Texture.EMPTY;
        if(source){
            texture=TexturePool.newTexture(source);
        }
        super({texture,width,height});
        if(!source){
            texture.off('update',this.onViewUpdate, this);
        }
    }
    destroy(opts){
        opts=opts||{children:true};
        if(opts.texture){
            opts.texture=false;
        }
        if(opts.textureSource){
            opts.textureSource=false;
        }
        this.releaseTextureAbout();
        super.destroy(opts);
    }
    set source(value){
        if(this.texture.source==value){
            ImageManager.releaseUnknowImageSource(value);
            return;
        };
        if(!value){
            if(this.texture.label=='EMPTY')return;
            this.releaseTextureAbout();
        }else{
            let texture=this.texture;
            if(texture.label=='EMPTY'){
                texture=TexturePool.newTexture(value);
                this.texture=texture;
            }else{
                let oldSource=this.texture._source;

                this.texture.noFrame=true;
                this.texture.source=value;
                this.texture.update();
                this.texture.noFrame=false;
                value.off('resize',this.texture.update,this.texture);

                ImageManager.releaseUnknowImageSource(oldSource);
            }
        }
    }
    move(x,y){
        this.x=x;
        this.y=y;
    }

    isValid(){
        return this.texture?.label!='EMPTY';
    }

    releaseTextureAbout(){
        let retTexture=this.texture;
        this.texture=Texture.EMPTY;
        this.texture.off('update',this.onViewUpdate, this);

        ImageManager.releaseUnknowImageSource(retTexture.source);
        
        TexturePool.releaseTexture(retTexture);
    }
}